package com.sws.worktive;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.entity.mime.HttpMultipartMode;
import ch.boye.httpclientandroidlib.entity.mime.MultipartEntityBuilder;
import ch.boye.httpclientandroidlib.entity.mime.content.FileBody;

import com.sws.worktive.task.ServerDownload;
import com.sws.worktive.task.ServerResponse;
import com.sws.worktive.util.ConnectionDector;
import com.sws.worktive.util.Constant;
import com.sws.worktive.util.WT_Prefrences;

public class PhotoPostingFragment extends BaseFragment implements OnClickListener,
		ServerResponse {

	ImageView postImage;

	int targetW = 300, targetH = 300;

	LinearLayout ll_back;
	boolean isCameraPreview;
	EditText edtDescription, edtPhoneNumber, edtZipCode;
	Spinner spn_MilesRadius, spn_JobTitle, spn_JobType, spn_Language;

	File binaryImage;
	int val_JobType, val_Language, val_JobCategory;
	List<NameValuePair> nameValuePairs;
	
	private static final String KEY_PICTURE_PATH = "key_picture_path";

	//======================== API ========================
	public static PhotoPostingFragment newInstance(
			FragmentManager fragmentManager, 
			String fragmentTag,
			String picturePath,
			boolean isCameraPreview){
		
		PhotoPostingFragment photoPostingFragment = (PhotoPostingFragment) fragmentManager.findFragmentByTag(fragmentTag);
		if (photoPostingFragment == null) {
			photoPostingFragment = new PhotoPostingFragment();
			
			Bundle bundle = new Bundle();
			bundle.putString(KEY_PICTURE_PATH, picturePath);
			bundle.putBoolean("isCamera", isCameraPreview);
			photoPostingFragment.setArguments(bundle);		
			
			return photoPostingFragment;
		}
		return null;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ConnectionDector connectionDector = new ConnectionDector(
				PhotoPostingFragment.this.getActivity());
		if (connectionDector.isConnectingToInternet()) {
			if (((DrawerFragment) getActivity()).arrCategories.size() == 0) {
				
				((DrawerFragment) getActivity()).mProgressDialog = ProgressDialog
						.show(getActivity(), "", getActivity().getResources()
								.getString(R.string.posting_jobs));
				ServerDownload serverDownload = new ServerDownload(
						getActivity(), PhotoPostingFragment.this,
						Constant.TAG_CATEGORY_REQUEST);
				serverDownload.execute(nameValuePairs);
				
			}
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.photoposting_screen, container,
				false);

		ll_back = (LinearLayout) view.findViewById(R.id.layout_back);
		ll_back.setOnClickListener(this);
		TextView txtHeader = (TextView) view.findViewById(R.id.screen_title);
		txtHeader.setText(getResources().getString(R.string.photo_posting));

		edtDescription = (EditText) view.findViewById(R.id.edt_description);
		edtZipCode = (EditText) view.findViewById(R.id.edt_zipcode);
		edtPhoneNumber = (EditText) view.findViewById(R.id.edt_phoneno);

		view.findViewById(R.id.btn_post).setOnClickListener(this);

		// spn_MilesRadius = (Spinner) view.findViewById(R.id.spn_mile_radius);
		// ArrayAdapter<CharSequence> adapterMilesRadius = ArrayAdapter
		// .createFromResource(PhotoPostingScreen.this.getActivity(),
		// R.array.array_miles_radius, R.layout.spinner_item);
		// adapterMilesRadius.setDropDownViewResource(R.layout.spinner_item);
		// spn_MilesRadius.setAdapter(adapterMilesRadius);
		//
		// spn_MilesRadius.setOnItemSelectedListener(new
		// OnItemSelectedListener() {
		//
		// @Override
		// public void onItemSelected(AdapterView<?> arg0, View arg1,
		// int arg2, long arg3) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		// // TODO Auto-generated method stub
		//
		// }
		// });

		spn_JobTitle = (Spinner) view.findViewById(R.id.spn_job_title);
		// ArrayAdapter<CharSequence> adapterJobTitle = ArrayAdapter
		// .createFromResource(PhotoPostingScreen.this.getActivity(),
		// R.array.array_job_title, R.layout.spinner_item);

		((DrawerFragment) getActivity()).adapterJobTitle
				.setDropDownViewResource(R.layout.spinner_item);
		spn_JobTitle.setAdapter(((DrawerFragment) getActivity()).adapterJobTitle);
		spn_JobTitle.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (arg2 == 0) {

				} else {
					val_JobCategory = arg2;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		spn_JobType = (Spinner) view.findViewById(R.id.spn_job_type);
		ArrayAdapter<CharSequence> adapterJobType = ArrayAdapter
				.createFromResource(PhotoPostingFragment.this.getActivity(),
						R.array.array_job_type, R.layout.spinner_item);

		adapterJobType.setDropDownViewResource(R.layout.spinner_item);
		spn_JobType.setAdapter(adapterJobType);
		spn_JobType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == 0) {

				} else {
					val_JobType = arg2;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		spn_Language = (Spinner) view.findViewById(R.id.spn_language);
		ArrayAdapter<CharSequence> adapterLanguage = ArrayAdapter
				.createFromResource(PhotoPostingFragment.this.getActivity(),
						R.array.array_languages, R.layout.spinner_item);

		adapterLanguage.setDropDownViewResource(R.layout.spinner_item);
		spn_Language.setAdapter(adapterLanguage);
		spn_Language.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == 0) {

				} else {
					val_Language = arg2;
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		postImage = (ImageView) view.findViewById(R.id.img_posting);
		isCameraPreview = getArguments().getBoolean("isCamera");
		setImage(getArguments().getString(KEY_PICTURE_PATH));

		return view;
	}

	public void setImage(final String path) {

		// Get the dimensions of the bitmap
		// ViewTreeObserver vto = postImage.getViewTreeObserver();
		// vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
		// public boolean onPreDraw() {
		// targetH = postImage.getMeasuredHeight();
		// targetW = postImage.getMeasuredWidth();
		// // Log.e("hilength", "Height: " + targetH + " Width: " +
		// // targetW);
		//
		// return true;
		// }
		// });

		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, bmOptions);
		int photoW = bmOptions.outWidth;
		int photoH = bmOptions.outHeight;

		// Determine how much to scale down the image
		int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

		// Decode the image file into a Bitmap sized to fill the View
		bmOptions.inJustDecodeBounds = false;
		bmOptions.inSampleSize = scaleFactor;
		bmOptions.inPurgeable = true;

		Bitmap bitmap = BitmapFactory.decodeFile(path, bmOptions);
		if (bitmap != null) {
			if (isCameraPreview) {
				// Bitmap rotatedBitmap = rotateImage(bitmap, 90);
				// if (rotatedBitmap != null) {
				// postImage.setImageBitmap(rotatedBitmap);
				// // new AsynBase64().execute(rotatedBitmap);
				// }

				new RotateTask(postImage).execute(bitmap);
			} else {
				postImage.setImageBitmap(bitmap);
				new AsynBase64().execute(bitmap);
			}
		}

	}

	public class RotateTask extends AsyncTask<Bitmap, Void, Bitmap> {
		private WeakReference<ImageView> imgInputView;
		private WeakReference<Bitmap> rotateBitmap;

		public RotateTask(ImageView imgInputView) {
			this.imgInputView = new WeakReference<ImageView>(imgInputView);
		}

		@Override
		protected void onPreExecute() {
			// if you want to show progress dialog
		}

		@Override
		protected Bitmap doInBackground(Bitmap... params) {
			Matrix matrix = new Matrix();
			matrix.postRotate(90);
			rotateBitmap = new WeakReference<Bitmap>(Bitmap.createBitmap(
					params[0], 0, 0, params[0].getWidth(),
					params[0].getHeight(), matrix, true));
			return rotateBitmap.get();
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// dismiss progress dialog
			imgInputView.get().setImageBitmap(result);
			new AsynBase64().execute(result);
		}
	}

	public static Bitmap rotateImage(Bitmap src, float degree) {
		// create new matrix
		// Matrix matrix = new Matrix();
		// // setup rotation degree
		// matrix.postRotate(degree);
		// Bitmap bmp = Bitmap.createBitmap(src, 0, 0, src.getWidth(),
		// src.getHeight(), matrix, true);

		Matrix matrix = new Matrix();
		matrix.postRotate(90);
		Bitmap bmp = Bitmap.createBitmap(src, 0, 0, src.getWidth(),
				src.getHeight(), matrix, true);
		ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.JPEG, 100, bmpStream);
		// iv.setImageBitmap(rotated);

		return bmp;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.layout_back:
			FragmentManager fragmentManager = getActivity()
					.getSupportFragmentManager();
			fragmentManager.popBackStack();
			break;

		case R.id.btn_post:

			if (binaryImage == null) {
				Toast.makeText(getActivity(), "Invalid Image..",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (edtZipCode.getText().toString().length() < 5) {
				Toast.makeText(getActivity(), "Enter valid zipcode..",
						Toast.LENGTH_SHORT).show();
				return;
			} else {
				ConnectionDector connectionDector = new ConnectionDector(
						PhotoPostingFragment.this.getActivity());
				if (connectionDector.isConnectingToInternet()) {
					((DrawerFragment) getActivity()).mProgressDialog = ProgressDialog
							.show(getActivity(),
									"",
									getActivity().getResources().getString(
											R.string.posting_jobs));

					ServerDownload serverDownload = new ServerDownload(
							PhotoPostingFragment.this.getActivity(),
							PhotoPostingFragment.this, 
							Constant.TAG_POST_REQUEST,
							createHttpEntity());
					serverDownload.execute(postingRequest());
				} else {
					Toast.makeText(
							PhotoPostingFragment.this.getActivity(),
							getResources().getString(
									R.string.no_internet_connection),
							Toast.LENGTH_SHORT).show();
				}
			}
			break;

		default:
			break;
		}

	}

	// Generating binary data for image

	class AsynBase64 extends AsyncTask<Bitmap, Void, File> {
		@Override
		protected File doInBackground(Bitmap... params) {
			if (params[0] == null)
				return null;

			
			
			return saveBitmapToCacheFile(params[0]);
		}

		@Override
		protected void onPostExecute(File result) {
			super.onPostExecute(result);
			binaryImage = result;
		}
	}
	
	private File saveBitmapToCacheFile(Bitmap bitmap){
		//create a file to write bitmap data
		try {
			File f = new File(getActivity().getCacheDir(), "testImage");
			f.createNewFile();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
			byte[] bitmapdata = bos.toByteArray();

			//write the bytes in file
			FileOutputStream fos = new FileOutputStream(f);
			fos.write(bitmapdata);
			fos.flush();
			fos.close();
			return f;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
	}

	List<NameValuePair> postingRequest() {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair(Constant.API_PASSWORD,
				Constant.PASSWORD_VALUE));
//		nameValuePairs.add(new BasicNameValuePair(Constant.BINARY_IMAGE,
//				new FileBody(binaryImage));
		
		nameValuePairs.add(new BasicNameValuePair(Constant.PHONE_NUMBER,
				edtPhoneNumber.getText().toString()));
		nameValuePairs.add(new BasicNameValuePair(Constant.POST_JOB_TYPE,
				val_JobType + ""));
		nameValuePairs.add(new BasicNameValuePair(Constant.ZIPCODE, edtZipCode
				.getText().toString()));
		nameValuePairs.add(new BasicNameValuePair(Constant.LANGUAGE,
				val_Language + ""));
		nameValuePairs.add(new BasicNameValuePair(Constant.CATEGORY,
				val_JobCategory + ""));

		return nameValuePairs;

	}
	
	private HttpEntity createHttpEntity(){
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		builder.addPart("file", new FileBody(binaryImage));  
	    builder.addTextBody(Constant.API_PASSWORD, Constant.PASSWORD_VALUE);
	    builder.addTextBody(Constant.PHONE_NUMBER, edtPhoneNumber.getText().toString());
	    builder.addTextBody(Constant.POST_JOB_TYPE,  val_JobType + "");
	    builder.addTextBody(Constant.ZIPCODE,  edtZipCode
				.getText().toString());
	    builder.addTextBody(Constant.LANGUAGE,  val_Language + "");
	    builder.addTextBody(Constant.CATEGORY,  val_JobCategory + "");
	    final HttpEntity yourEntity = builder.build();
		
		return yourEntity;
	}

	@Override
	public void httpResponse(JSONObject jsonObject, String requestTag) {
		
		if (((DrawerFragment) getActivity()).mProgressDialog.isShowing()) {
			((DrawerFragment) getActivity()).mProgressDialog.dismiss();
		}
		
		if (requestTag.equals(Constant.TAG_POST_REQUEST)) {
			if (jsonObject != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonObject.toString());
					if (jsonObj.optInt(Constant.STATUS) == 1) {

						WT_Prefrences prefrences = new WT_Prefrences(
								PhotoPostingFragment.this.getActivity());
						prefrences.setLastPostTime(System.currentTimeMillis());
						prefrences.setPostAvail(prefrences.getPostAvail() - 1);
						Log.v("CURRENT POST TIME", System.currentTimeMillis()
								+ "");

						Toast.makeText(PhotoPostingFragment.this.getActivity(),
								jsonObj.optString(Constant.MESSAGE),
								Toast.LENGTH_SHORT).show();

						((DrawerFragment) PhotoPostingFragment.this.getActivity()).arrJobs
								.clear();
						FragmentManager fragmentManager = getActivity()
								.getSupportFragmentManager();
						fragmentManager.popBackStack();
					} else {

						Toast.makeText(PhotoPostingFragment.this.getActivity(),
								jsonObj.optString(Constant.MESSAGE),
								Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		} else if (requestTag.equals(Constant.TAG_CATEGORY_REQUEST)) {

			((DrawerFragment) getActivity())
					.startJsonParser4RCategory(jsonObject);
		}

	}

}
